﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using UFIDA.U9.AIT.OpenAPIBE;
using UFIDA.U9.ISV.U9CMobileAppsISV.CommonTools;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.Collections;

namespace ufida.u9.ait.openapi.utils
{
    /// <summary>
    /// HTTP调用工具类
    /// 用于调用外部接口
    /// </summary>
    public class HttpUtils
    {
        /// <summary>
        /// get请求
        /// 记录DB日志,Log日志
        /// </summary>
        /// <param name="url">调用地址</param>
        /// <param name="parms">调用参数</param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> GetMapList(string url, Dictionary<string, object> parms, Dictionary<String, String> head = null)
        {
            string retstr = Get(url, parms, head);
            List<Dictionary<string, object>> list = JSONUtils.toMapList(retstr);
            return list;
        }

        /// <summary>
        /// get请求
        /// 记录DB日志,Log日志
        /// </summary>
        /// <param name="url">调用地址</param>
        /// <param name="parms">调用参数</param>
        /// <returns></returns>
        public static Dictionary<string, object> GetMap(string url, Dictionary<string, object> parms, Dictionary<String, String> head = null)
        {
            string retstr = Get(url,parms,head);
            Dictionary<string, object> retdict = JSONUtils.toMap(retstr);
            return retdict;
        }

        /// <summary>
        /// get请求
        /// 记录DB日志,Log日志
        /// </summary>
        /// <param name="url">调用地址</param>
        /// <param name="parms">调用参数</param>
        /// <returns></returns>
        public static string Get(string url,Dictionary<string,object> parms,Dictionary<String, String> head = null)
        {
            string url1 = url;
            if (parms != null && parms.Count() > 0)
            {
                // 创建查询参数集合
                NameValueCollection queryParameters = HttpUtility.ParseQueryString(string.Empty);
                foreach (var item in parms)
                {
                    queryParameters[item.Key] = item.Value.ToString();
                }
                url1=url1+ "?" + queryParameters;
            }
            return Get(url1,head);
        }
        /// <summary>
        /// get请求,参数自行拼接
        /// 记录DB日志,Log日志
        /// </summary>
        /// <param name="url"></param>
        /// <param name="head"></param>
        /// <returns></returns>
        public static string Get(string url,Dictionary<String, String> head = null)
        {
            string retstr = "";
            int retcode = 200;
            string errstr = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.UserAgent = null;
                //request.Timeout = Timeout;
                // 设置请求头
                if (head != null)
                {
                    foreach (var item in head)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }
                //发送请求,获取返回值
                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
                retcode = (int)httpWebResponse.StatusCode;
                if (httpWebResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception($"Get请求失败,URL[{url}],返回码[{retcode}]");
                }
                //处理返回值
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                retstr = streamReader.ReadToEnd();

                streamReader.Close();
                responseStream.Close();
                httpWebResponse.Close();

                return retstr;
            }catch (Exception ex)
            {
                //这里只处理了系统报错,未对返回JSON解析
                errstr = ex.Message;
                throw new Exception($"Get请求失败,URL[{url}],错误消息:{ex.Message}", ex);
            }
            finally
            {
                //写入Log日志
                LogUtils.Log($"远程调用:[{url}]");
                LogUtils.Log($"retstr:[{retstr}]");
                //写入DB日志
                U9Utils.DBLog(url, "get", "", retstr, retcode, errstr);
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data">body数据,json格式</param>
        /// <param name="head">头数据</param>
        /// <returns></returns>
        public static Dictionary<string, object> PostMap(string url, string data, Dictionary<String, String> head = null)
        {
            string retstr = Post(url, data, head);
            Dictionary<string, object> retdict = JSONUtils.toMap(retstr);
            return retdict;
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data">body数据,json格式</param>
        /// <param name="head">头数据</param>
        /// <returns></returns>
        public static string Post(string url, string data,Dictionary<String,String> head=null)
        {
            string retstr = "";
            string errstr = "";
            int retcode = 200;
            HttpWebRequest request = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/json";
                if (data == null) throw new Exception("data不能为空");

                // 设置请求头
                if (head != null) { 
                    foreach(var item in head)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }

                //body写入json数据
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8))
                {
                    writer.Write(data);
                }

                //发送请求,获取返回值
                httpWebResponse = request.GetResponse() as HttpWebResponse;
                retcode = (int)httpWebResponse.StatusCode;
                if (httpWebResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception($"Post请求失败,URL[{url}],返回码[{retcode}]");
                }
                //处理返回值
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                retstr = streamReader.ReadToEnd();

                streamReader.Close();
                responseStream.Close();
                httpWebResponse.Close();

                return retstr;
            }catch(Exception ex)
            {
                errstr = ex.Message;
                throw new Exception($"Post请求失败,URL[{url}],错误消息:{ex.Message}", ex);
            }
            finally
            {
                //写入Log日志
                LogUtils.Log($"远程调用:[{url}]");
                LogUtils.Log($"retstr:[{retstr}]");
                //写入AIT日志
                U9Utils.DBLog(url,"post", data, retstr, retcode,errstr);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url">上传文件的接口地址</param>
        /// <param name="file">要上传的文件地址</param>
        /// <returns>返回上传的响应结果</returns>
        public static string PostFile(string url, string file)
        {
            string result = String.Empty;
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                byte[] responseArray = client.UploadFile(url, "POST", file);
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                Console.WriteLine("上传result:" + result);
            }
            catch (Exception ex)
            {
                //result = "Error:" + ex.Message;
                //Console.WriteLine("发送GET请求出现异常：" + ex.Message);
                throw new Exception($"上传文件失败,url[{url}],错误消息:{ex.Message}", ex);
            }
            return result;
        }

        /// <summary>
        /// 从URL下载文件,并存储到filePath
        /// </summary>
        /// <param name="url">文件下载URL</param>
        /// <param name="filePath">文件路径,含文件名</param>
        public static bool DownloadFile(string url, string filePath)
        {
            bool result = false;
            
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                //request.Accept = "*/*";
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileUtils.WriteBinFile(filePath, responseStream);
                responseStream.Close();
                response.Close();

                result = true;
            }
            catch (Exception ex)
            {
                throw new Exception($"下载文件失败,url[{url}],错误消息:{ex.Message}", ex);
            }
            return result;
        }
    }
}
